<?php

class AuthItemController extends Controller
{
    private $configs = array(0 => array('name' => 'operation' , 'displayColor' => 'red'),
                             1 => array('name' => 'task' , 'displayColor' => 'purple'),
                             2 => array('name' => 'role' , 'displayColor' => 'green'),
                            );

    public function actionAdd()
    {
        $model = new AuthItem();
        $itemChild = new AuthItemChild();
        if(isset($_POST['AuthItem'],$_POST['AuthItemChild']))
        {
            $model->attributes = $_POST['AuthItem'];
            $modelResult = $model->save();
            $itemChildResult = true;
            if(trim($_POST['AuthItemChild']['parent']) != '')
            {
                $_POST['AuthItemChild']['child'] = $_POST['AuthItem']['name'];
                $itemChild->attributes = $_POST['AuthItemChild'];
                $itemChildResult = $itemChild->save();
            }
            
            if($itemChildResult and $modelResult)
            {
                Yii::app()->user->setFlash('success',"Item added!");
                $this->redirect(array('edit','name' => $model->name));
            }
            else
            {
                throw new CHttpException(505,'System Error');
            }
        }

        $this->render('add', array('model' => $model, 
                                   'title' => 'Create', 
                                   'itemChild' => new AuthItemChild, 
                                   'dropdown'  => $this->findAllParents()));
    }

    public function actionEdit()
    {
        if(isset($_GET['name']))
        {
            $name = $_GET['name'];
        }
        else
        {
            throw new CHttpException(404,'invalid request');
        }
         
        $item      = AuthItem::model()->findByPk($name);
        $itemChild = $item->authItemChildren1;
        $itemChild = $itemChild[0];
        
        if($item == NULL)
        {
            throw new CHttpException(404,'Item NOT found');
        }
        
        if(isset($_POST['AuthItem'], $_POST['AuthItemChild']))
        {
            $itemChild->attributes = $_POST['AuthItemChild'];
            $item->attributes      = $_POST['AuthItem'];
            if($item->save() and $itemChild->save())
            {
                Yii::app()->user->setFlash('success',"Item saved!");
                $this->redirect(array('edit', 'name' => $item->name));
            }
        }
        

        $this->render('edit', array('model' => $item, 
                                    'itemChild' => $itemChild ,
                                    'dropdown'  => $this->findAllParents($item),
                                    'title' => 'Edit '.$name)); 
    }
    
    public function findAllParents($item = '')
    {
        $itemChild = $item->authItemChildren1;
        $itemChild = $itemChild[0];

        if($item instanceof AuthItem)
        {
            //only when the instance is AuthItem , do following otherwise return false
            $criteria=new CDbCriteria;
            $criteria->select=array('parent');
            $criteria->distinct=true;
            
            $criteria->alias = 'tbl_auth_item_child';
            $criteria->join='LEFT JOIN tbl_auth_item ON tbl_auth_item.name = tbl_auth_item_child.parent';
            
            if($item->type == 2)
            {
                //input item is role
                $criteria->condition='tbl_auth_item.type = 2 ';
            }
            else if($item->type == 1 or $item->type == 0)
            {
                //input item is task
                $criteria->condition='tbl_auth_item.type = 2 OR tbl_auth_item.type = 1';
            }

            $criteria->condition='`tbl_auth_item_child`.child != "'.$item->name.'" AND `tbl_auth_item_child`.parent != "'.$item->name.'"';
            
            $return = CHtml::listData(AuthItemChild::model()->findAll($criteria), 'parent', 'parent');

            if($itemChild->parent)
            {
                $return[$itemChild->parent] = $itemChild->parent;
            }

            return array_unique($return);
        }
        else if($item == '')
        {
            //get all roles and tasks
            //only when the instance is AuthItem , do following otherwise return false
            $criteria=new CDbCriteria;
            $criteria->select=array('parent');
            $criteria->distinct=true;
            $criteria->alias = 'tbl_auth_item_child';
            $criteria->join='LEFT JOIN tbl_auth_item ON tbl_auth_item.name = tbl_auth_item_child.parent';
            $criteria->condition='tbl_auth_item.type = 2 OR tbl_auth_item.type = 1';
            return CHtml::listData(AuthItemChild::model()->findAll($criteria), 'parent', 'parent');
        }
        else
        {
            return false;
        }
    }

	public function actionIndex()
	{
        if(Yii::app()->user->role !== Yii::app()->params['SUPER'])
        {
            throw new CHttpException(404,'You are not authorized to do such action!');
        }
        
		$criteria=new CDbCriteria;
		$criteria->condition='type > 0';
        $this->render('index', array('items'    => AuthItem::model()->findAll($criteria),
                                      'configs' => $this->configs,
                                      'title'   => 'Roles & Operations & Tasks'));

	}

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}
